<? global $SERVER; ?>
<style type="text/css">
	textarea.wysiwyg {
		width: 100%;
	}
</style>
<div class="localization" style="padding:10px 20px 10px 20px;">
<form id="hformx<?=$arr_param["texts"][0]['identifier']?>" method="post" action="" onsubmit="">
    <div class="formfield" style="white-space:nowrap;">
    	<label for="name">Text Identifier:</label><br/>
    	<input type="hidden" name="texts[old_identifier]" value="<%=(strlen($arr_param['texts'][0]['identifier']) > 0 ? $arr_param['text']['path'].$arr_param['text']['name'] : '')%>" />
    	<input type="hidden" name="texts[identifier]" value="#text.path" />
        <? if (substr($arr_param["text"]["path"], 0, 4) == "cms.") { ?>
            <? $arr_param["text"]["type"] = $int_textType = 2; ?>
        <? } ?>
    	<input type="hidden" class="id-value" name="texts[texts_id]" value="<?=(int)$_SESSION['texts_id']?>" />
    	<c:if cond="strlen($arr_param['texts'][0][identifier])>0 && false">
        	<input type="hidden" id="text_name_<?=(int)$arr_param['texts'][0]['texts_id']?>" name="texts[name]" value="#text.name" /> 
   	    	<span style="font-size:10px;color:#999;">#text.path</span><span class="value">#text.name</span>    	
        <c:else />
        	<span style="font-size:10px;color:#999;">#text.path</span><input type="text" id="text_name_<?=(int)$arr_param['texts'][0]['texts_id']?>" name="texts[name]" value="#text.name" />            	   
    	</c:if>
    </div>
    <div class="formfield">
        <label>Content Size:</label><br/>
        <select name="texts[type]" size="1" onchange="setNewTextType(this.value, '<?=$arr_param['texts'][0][identifier]?>');">
            <option value="0"<?=(int)$arr_param["text"]["type"] == 0 ? "selected='selected'" : ""?>>Single Line</option>
            <option value="1"<?=(int)$arr_param["text"]["type"] == 1 ? "selected='selected'" : ""?>>Multiple Lines</option>
<? if (substr($arr_param["text"]["path"], 0, 4) == "cms.") { ?>
            <option value="2"<?=(int)$arr_param["text"]["type"] == 2 ? "selected='selected'" : ""?>>Page Template</option>
<? } ?>            
        </select>
    </div>
    <c:if cond="$arr_param['text']['type'] == 2 && count($arr_param['decorators']) > 0">
        <div class="formfield">
            <label>Decorator:</label><br/>
            <select name="texts[decorator]" size="1">
                <option value="">Please choose</option>
                <c:foreach var="decorators" name="decorator">
                    <c:if cond="$arr_param['text']['decorator'] == $arr_param['decorator']['name']">
                        <option value="#decorator.name" selected="selected">#decorator.name</option>
                    <c:else />
                        <option value="#decorator.name">#decorator.name</option>
                    </c:if>
                </c:foreach>
            </select>
        </div>
    </c:if>
    <c:if cond="$arr_param['text']['type'] == 2 && substr($arr_param['text']['path'], 0, 4) == 'cms.'">
        <div class="formfield">
            <label class="url" style="white-space:nowrap;"><?=$SERVER?>static/<span class='url_preview'><?=preg_replace('#^cms/#', '', str_replace(".", "/", $arr_param["texts"][0]["identifier"]))?></span>.html</label><br/>
            <a href="<?=$SERVER?>static/<?=preg_replace('#^cms/#', '', str_replace(".", "/", $arr_param["texts"][0]["identifier"]))?>.html" <?=($arr_param['texts'][0]['texts_id'] <= 0 ? 'style="color:#999;cursor:default;" onclick="return false;"': "")?> target="preview">Show this page</a>
        </div>
    </c:if>
	<div style="clear:both;"></div>
    <br/>
    <c:if cond="$arr_param['text']['type'] == 2 && substr($arr_param['text']['path'], 0, 4) == 'cms.'">
    <div class="seo">
	<div class="formfield">
		<label>SEO Title:</label><br/>
		<input type="text" name="texts[title]" value="#text.title" style="width:200px;" />
	</div>
	<div class="formfield">
		<label>SEO META description:</label><br/>
		<textarea name="texts[description]" style="border:1px solid #ccc;width:350px;height:30px;">#text.description</textarea>
	</div>
	<div style="clear:both;"></div>
    </div>
    </c:if>
    <div id="texts_tabs_<?=$arr_param['texts'][0]['identifier']?>">
    	<div class="x-tab" title="Contents">    
		    <div id="texts_<?=$arr_param["texts"][0]['identifier']?>" style="padding-left: 10px;">
			    <c:foreach var="texts" name="texta">
			    <div class="formfield" style="<? if ($arr_param['text']['type'] > 0) { ?>float:none;width:auto;<? } else { ?>width:auto<? } ?>;margin-right: <?=($arr_param["text"]["type"] == 2 ? 0 : 20)?>px;margin-bottom: 20px;">
			    	<label for="contentl#texta.texts_id">in <span id="">#texta.name</span>:</label><br/> <!-- make language be editable and removable! -->
			        <? if ($arr_param["text"]["type"] <= 0) { ?>
			            <input type="text" name="texts[content][#texta.language_id]" id="contentl#texta.texts_id" value="<?=htmlspecialchars($arr_param['texta']['content'])?>" style="width:400px;" />
			        <? } else { ?>
			            <div style="display:<?=($arr_param['text']['type'] == '1') ? "inline-" : ""?>block;min-width: 400px;">
			                <? if ($arr_param["text"]["type"] == 1) { ?>
			                	<textarea class="wysiwyg" rel="file_browser_callback=wysiwygFileBrowser|theme_advanced_toolbar_align=center" name="texts[content][#texta.language_id]" id="contentl#texta.texts_id" cols="80" rows="30"><c:print value="texta.content"/></textarea>
			                <? } else { ?>
			                	<textarea class="wysiwyg" rel="file_browser_callback=wysiwygFileBrowser|theme_advanced_toolbar_align=center|plugins=,autoresize" name="texts[content][#texta.language_id]" id="contentl#texta.texts_id" cols="80" rows="30"><c:print value="texta.content"/></textarea>
			                <? } ?>
			            </div>
			        <? } ?>
			    	<div style="clear:both;"></div>
			    </div>
			    </c:foreach>
    		</div>
    	</div>
    	<div class="x-tab" title="Custom Attributes">
		    <div id="texts_attr_<?=$arr_param['texts'][0]['identifier']?>" style="padding: 10px;">
		    	<c:foreach var="custom_struct.data.id" name="value" key="key">
		    		<div class="formfield" style="float:none;margin-top: 10px;">
		    			<div class="label"><%=$arr_param['custom_struct']['data']['name'][$key]%> <a href="javascript:" title="ID: #local.value"> ? </a></div>
		    			<div class="value">
		    				<c:if cond="$arr_param['custom_struct']['data']['type'][$key] == 'text' || $arr_param['custom_struct']['data']['type'][$key] == 'html'">
		    					<textarea id="l_<?=microtime(true)?><%=$key%>" class="<%=$arr_param['custom_struct']['data']['type'][$key] == 'html'?'wysiwyg':''%>" style="border: 1px solid #ccc;" rows="5" name="texts[custom][#local.value]"><%=$arr_param['text']['custom'][$value]%></textarea>
		    				<c:else/>
		    					<input name="texts[custom][#local.value]" value="<%=$arr_param['text']['custom'][$value]%>" type="<%=$arr_param['custom_struct']['data']['type'][$key]%>"/>
		    				</c:if>
		    			</div>
		    		</div>
		    	</c:foreach>
		    	<button type="button" id="cadefbtn">Edit Custom Attribute definitions</button>
		    </div>
    	</div>
    </div>
    <div id="ca-def#texts.0.identifier" style="display: none;">
    	<table border="0" style="width: 100%;">
    		<thead>
	    		<tr>
	    			<th>ID</th>
	    			<th>Display Name</th>
	    			<th>Type</th>
	    			<th></th>
	    		</tr>
    		</thead>
    		<tfoot>
    			<tr>
    				<th colspan="4" align="right"><button type="button" onclick="this.up('table').down('tbody').insert($('cadef-tpl-#texts.0.identifier').innerHTML);">add attribute</button></th>
    			</tr>
    		</tfoot>
    		<tbody id="ca-def-items-#texts.0.identifier">
    		<c:foreach var="custom_struct.data.id" key="key" name="obj">
    			<tr>
    				<td><input name="custom[data][id][]" value="#local.obj"/></td>
    				<td><input name="custom[data][name][]" value="<%=$arr_param['custom_struct']['data']['name'][$key]%>"/></td>
    				<td><select name="custom[data][type][]">
	    					<option value="" disabled="disabled">Select...</option>
	    					<option value="string" <%=($arr_param['custom_struct']['data']['type'][$key] == 'string' ? 'selected="selected"' : '')%>>String</option> 
	    					<option value="text" <%=($arr_param['custom_struct']['data']['type'][$key] == 'text' ? 'selected="selected"' : '')%>>Text</option> 
	    					<option value="html" <%=($arr_param['custom_struct']['data']['type'][$key] == 'html' ? 'selected="selected"' : '')%>>HTML Text</option>
	    					<option value="number" <%=($arr_param['custom_struct']['data']['type'][$key] == 'number' ? 'selected="selected"' : '')%>>Number</option> 
	    				</select>
					</td>
					<td>
						<a href="javascript:" onclick="this.up('tr').remove();"><img src="templates/builder/images/delete.gif" alt="" border='0'/></a>
					</td>
    			</tr>
    		</c:foreach>
    		</tbody>
    	</table>
    	<div style="display:none;">
   			<table><tbody id="cadef-tpl-#texts.0.identifier"><tr>
				<td><input name="custom[data][id][]" value=""/></td>
				<td><input name="custom[data][name][]" value=""/></td>
				<td><select name="custom[data][type][]">
    					<option value="" disabled="disabled">Select...</option>
    					<option value="string">String</option> 
    					<option value="text">Text</option> 
    					<option value="html">HTML Text</option>
    					<option value="number">Number</option> 
    				</select>
				</td>
				<td>
					<a href="javascript:" onclick="this.up('tr').remove();"><img src="templates/builder/images/delete.gif" alt="" border='0'/></a>
				</td>
			</tr>  </tbody></table>  	         
    	</div>
    </div>
	<div style="clear:both;"></div>
	<script type="text/javascript">
	//<![CDATA[
		setTimeout(function() {
			// init tabs for custom attributes
			window["textTabs<?=$arr_param['texts'][0]['identifier']?>"] = new Ext.TabPanel({
			    applyTo: 'texts_tabs_<?=$arr_param['texts'][0]['identifier']?>',
			    activeTab: 0,
			    width: "auto",
			    defaults: {
			    	width: "auto",
				    autoScroll: true,
			    	closable: false,
				    listeners: {
				    	activate: function(p) {}
				    }
			    },
			    deferredRender: false,
			    height: (parseInt($("hformx<?=$arr_param['texts'][0]['identifier']?>").parentNode.parentNode.style.height) - 170),
			    autoScroll: true,
			    autoTabs: true
			});
			$("cadefbtn").observe('click', function(event){
				// open window and list the existing attributes
				window.cadefWin = new Ext.Window({
					layout: "fit",
					title: "Edit Custom Attribute Definitions",
					width: 400,
					height: 300,
					plain: true,
					items: new Ext.Panel({
						deferredRender: false,
						autoScroll: true,
						border: false,
						id: "form-content-cadef",
						html: $("ca-def#texts.0.identifier").innerHTML
					}),
					buttons: [{
						text: "Save",
						handler: function() {
							// send ajax call to store it
							var items = "";
							$("form-content-cadef").down("tbody").select("input, select").each(function(item){
								items += "&" + item.serialize();
							});
							invoke(null, "builder:editText&check=cadef", items, true, function(req){
								Builder.reloadTab("x_#texts.0.identifier");
								window.cadefWin.close();
							});
						}						
					}, {
						text: "Cancel",
						handler: function() {
							window.cadefWin.hide();
						}						
					}]
				});
				cadefWin.show();
			});
			
			window.wysiwygFileBrowser = function(field_name, url, type, win) {
				var cmsURL = "<? global $SERVER; echo $SERVER;?>?event=builder:fileBrowser";
			    if (cmsURL.indexOf("?") < 0) {
			        //add the type as the only query parameter
			        cmsURL = cmsURL + "?type=" + type;
			    } else {
			        //add the type as an additional query parameter
			        // (PHP session ID is now included if there is one at all)
			        cmsURL = cmsURL + "&type=" + type;
			    }

			    tinyMCE.activeEditor.windowManager.open({
			        file : cmsURL,
			        title : 'Media Browser',
			        width : 620,  // Your dimensions may differ - toy around with them!
			        height : 400,
			        resizable : "yes",
			        inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
			        close_previous : "no"
			    }, {
			        window : win,
			        input : field_name
			    });
			    return false;
			};
            window.setNewTextType = function(type, id) {
                if ($("hformx"+id).select(".id-value")[0].value > 0) {
                    new Ajax.Request("?event=builder:editText&texts_id="+$("hformx"+id).select(".id-value")[0].value+"&check=2", {
                        parameters: {
                            id: $("hformx"+id).select(".id-value")[0].value,
                            type: type
                        }, 
                        method: "POST", 
                        onSuccess: function(req) {
            		        Builder.reloadTab("x_"+id);
                        }
                    });
                } else {
                    // dynamically turn all fields into the new format...
                    var types = [
                        new Element("input", {type: "text", style: 'width: 400px;'}),
                        new Element("textarea", {"class": "wysiwyg", cols: 80, rows: 30}),
                        new Element("textarea", {"class": "wysiwyg", cols: 80, rows: 30})
                    ];
                    var tel = types[type];
                    $("texts_"+id).select("input, textarea").each(function(item) {
                    	if (item.nodeName.toUpperCase() == "TEXTAREA") {
                    		item.next("span.mceEditor").remove();
                    	}
                        var el = tel.cloneNode(true);
                        if (item._editor) {
//                            item._editor.removeInstance(item.id);
                        }
                        el.name = item.name;
                        el.id = item.id;
                        item.replace(el);
                    });
                    initWysiwyg();		  
                }
    	    };
    
            initWysiwyg();
			(Ext.getCmp("portlet_content_x_<?=strtolower($arr_param["texts"][0]['identifier'])?>") || Ext.getCmp("portlet_content_x_<?=$arr_param["texts"][0]['identifier']?>")).getTopToolbar().add([{
				xtype: "button",
				text: "Save",
				iconCls: "save",
				handler: function(e) {
				    $("hformx<?=$arr_param["texts"][0]['identifier']?>").select(".wysiwyg").each(function(item){
				        item.value = tinyMCE.get(item.id).getContent();
				    });
				    data = $("hformx<?=$arr_param["texts"][0]['identifier']?>").serialize(true);
				    data["texts[identifier]"] += data["texts[name]"];
				    new Ajax.Request("?event=builder:editText&check=1", {
				        method: "POST",
				        parameters: data, 
				        onSuccess: function(req) {
				           if ('<?=$arr_param['texts'][0]['identifier']?>'.length > 0 && <?=(int)$arr_param["texts"][0]["texts_id"]?> > 0) {
        						Ext.ux.util.msg("Saving completed.", "Your changes have been saved successfully.");
				           } else {
                                loadURL("?event=builder:home&open_nav=qwbuilder_langsPanel&open_tree="+data["texts[identifier]"]);
				           }
				        }
				    });
				}
			}, {
			    xtype: "button",
			    text: "Add Language",
			    iconCls: "locale",
			    handler: editLanguage=function(e) {
			        if (!e || !e.id || !e.abbr) {
			            e = {
			               id: 0,
			               name: "",
			               abbr: "",
			               "def": <?=(count($arr_param["texts"]) <= 0 ? "1" : "0")?>
			            };
			        }
					langWin=new Ext.Window({
						layout: "fit",
						title: (e.id <= 0 ? "Add" : "Edit")+" Language",
						iconCls: "locale",
						modal: true,
						shadow: true,
						width: 300,
						height: 200,
						plain: true,
						items: [langForm=new Ext.form.FormPanel({
						    url: "?event=builder:editLanguage&language_id="+e.id,
						    labelWidth: 100,
						    border: false,
						    hideBorders: true,
						    headerAsText: true,
						    bodyStyle: "padding-left:5px;padding-top:5px;",
						    padding: 10,
						    title: "Please enter language details:",
						    defaultType: "textfield",
    						monitorValid: true,
						    items: [{
						        fieldLabel: "Name",
						        name: "lang[name]",
						        value: e.name,
						        allowBlank: false
						    }, {
						        fieldLabel: "Language Code",
						        name: "lang[abbreviation]",
						        value: e.abbr,
						        allowBlank: false
						    }, {
						        xtype: "radiogroup",
						        fieldLabel: "Default Language",
						        items: [
						          {boxLabel: "yes", name: "lang_default", inputValue: "1", checked: (e["def"] == 1 ? true : false)},
						          {boxLabel: "no", name: "lang_default", inputValue: "0", checked: (e["def"] == 0 ? true : false)}
						        ]
						    }],
						    buttons: [{
						        text: "Save",
						        formBind: true,
						        handler: function() {
						           langForm.getForm().submit({
						               method: "POST",
						               success: function() {
                            		        Builder.reloadTab("x_<?=$arr_param["texts"][0]['identifier']?>");						                  
                            		        langWin.close();
						               },
						               failure: function() {
						                  Ext.Msg.alert("Error", "There was an error submitting your data. Please try again later.");
						               }
						           });
						        }
						    }, {
						        text: "Cancel",
						        handler: function() {
						            langWin.close();
						        }
						    }]
						})]
					});
			        langWin.show();
			    }
			}, {
			    xtype: "button",
			    text: "Edit Language",
			    iconCls: "edit",
			    menu: {
			       items: [
			         <? if (is_array($arr_param["texts"])) foreach ($arr_param["texts"] as $i => $text) { ?>
			             <? if ($i > 0) { ?>,<? } ?>
			             {
    		                  text: '<?=$text["name"]?>', 
    		                  iconCls: "locale", 
    		                  handler: function() {
    		                      editLanguage({
    		                          id: "<?=$text['language_id']?>",
    		                          abbr: "<?=$text['abbreviation']?>",
    		                          name: "<?=$text['name']?>",
    		                          "def": "<?=(int)$text['default']?>"
    		                      });
    		                  }
			             }
			         <? } ?>
			       ]
			    }
		    }, {
                text: "Delete Language",
                iconCls: "delete",
                menu: {
                    items: [
			         <? if (is_array($arr_param["texts"])) foreach ($arr_param["texts"] as $i => $text) { ?>
			             <? if ($i > 0) { ?>,<? } ?>
			             {
    		                  text: '<?=$text["name"]?>', 
    		                  iconCls: "locale", 
    		                  handler: function() {
    		                      Ext.Msg.confirm("Delete Language", "Do you really want to delete this whole language including all associated texts?", function(btn) {
    		                          if (btn == "yes") {
    		                              new Ajax.Request("?event=builder:editLanguage&delete=1&language_id=<?=$text['language_id']?>", {
    		                                  onSuccess: function(req) {
                                                loadURL("?event=builder:home&open_nav=qwbuilder_langsPanel");
		                                      }
    		                              });
    		                          }
    		                      });
    		                  }
			             }
			         <? } ?>
                    ]
                }
		    }]);
			(Ext.getCmp("portlet_content_x_<?=strtolower($arr_param["texts"][0]['identifier'])?>") || Ext.getCmp("portlet_content_x_<?=$arr_param["texts"][0]['identifier']?>")).getTopToolbar().doLayout();
			<? if (count($arr_param["texts"]) <= 0) { ?>
			editLanguage({});
			<? } ?>
			$("hformx<?=$arr_param["texts"][0]['identifier']?>").select("#text_name_<?=(int)$arr_param['texts'][0]['texts_id']?>").each(function(item) {
				item.observe("change", function(event) {
					$("hformx<?=$arr_param["texts"][0]['identifier']?>").select(".url_preview").each(function(p) {
						p.innerHTML = item.value;
					});
				});
			});
		}, 100);
	//]]>
	</script>
</form>
</div>
